package com.shiro.service.impl;

import com.shiro.dao.UserDao;
import com.shiro.dao.impl.UserDaoImpl;
import com.shiro.entity.User;
import com.shiro.service.UserService;
import com.shiro.utils.PasswordHelper;

import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

/**
 * 用户Service实现
 * <p>User: Zhang Kaitao
 * <p>Date: 14-1-28
 * <p>Version: 1.0
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDaoImpl();
    private PasswordHelper passwordHelper = new PasswordHelper();

    @Override
    public User createUser(User user) {
        //加密密码
        passwordHelper.encryptPassword(user);
        return userDao.createUser(user);
    }

    @Override
    public void changePassword(Long userId, String newPassword) {
        User user =userDao.findOne(userId);
        user.setPassword(newPassword);
        passwordHelper.encryptPassword(user);
        userDao.updateUser(user);
    }

    @Override
    public void correlationRoles(Long userId, Long... roleIds) {
        userDao.correlationRoles(userId, roleIds);
    }


    @Override
    public void uncorrelationRoles(Long userId, Long... roleIds) {
        userDao.uncorrelationRoles(userId, roleIds);
    }

    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    @Override
    public Set<String> findRoles(String username) {
        return userDao.findRoles(username);
    }

    @Override
    public Set<String> findPermissions(String username) {
        return userDao.findPermissions(username);
    }

	@Override
	public String login(String username, String password) {
		String error = null;
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
			subject.login(token);
		} catch (UnknownAccountException e) {
			error = "用户名错误";
			//e.printStackTrace();
		} catch (IncorrectCredentialsException e) {
			error = "密码错误";
			//e.printStackTrace();
		}catch (ExcessiveAttemptsException e) {
			error = "账户因登录错误次数太多";
			//e.printStackTrace();
		}catch (LockedAccountException e) {
			// 其他错误，比如锁定，如果想单独处理请单独catch 处理
			error = "账户锁定";
			//e.printStackTrace();
		}
		
		if(error!=null){
			return "false," + error;
		}
		return "true,登录成功";
	}

	@Override
	public boolean logout(){
		try{
			SecurityUtils.getSubject().logout();
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
